﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer;
using SqlServerWrapper;
using ResponseObject;
using BartonExtension;
using Model.User;
using Model;

namespace WebSrvs.NET
{
    /// <summary>
    /// ZK_NearByService 的摘要说明
    /// 
    [System.Web.Script.Services.ScriptService]
    [WebService(Namespace = "http://zker.hk/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class ZK_NearByService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string locationSync(long uid, double lat, double lon, string formatted_addr)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_user_location_info_update";
                    cmd.Parameters.Add("@uid", SqlDbType.BigInt).Value = uid;
                    cmd.Parameters.Add("@lat", SqlDbType.Float).Value = lat;
                    cmd.Parameters.Add("@lon", SqlDbType.Float).Value = lon;
                    cmd.Parameters.Add("@formatted_addr", SqlDbType.VarChar).Value = formatted_addr;
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string requestNearByPeople(long uid, double lat, double lon, double distance_filter)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_location_get_proper_nearby";
                    cmd.Parameters.Add("@uid", SqlDbType.BigInt).Value = uid;
                    cmd.Parameters.Add("@lat", SqlDbType.Float).Value = lat;
                    cmd.Parameters.Add("@lon", SqlDbType.Float).Value = lon;
                    cmd.Parameters.Add("@distance_filter", SqlDbType.Float).Value = distance_filter;
                    try
                    {
                        using(SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("nearby");
                            dt.Load(dr);
                            List<user_nearby> nearbyPeople = new List<user_nearby>();
                            foreach (DataRow row in dt.Rows)
                            {
                                user_nearby person = new user_nearby()
                                {
                                    uid = row["uid"].toInt64().Value,
                                    nickname = row["nickname"].ToString(),
                                    phone = row["phone"].toInt64().Value,
                                    region_id = row["region_id"].toInt32().Value,
                                    headicon = row["headicon_img_path"].ToString(),
                                    location_lat = row["lat"].toFloat().Value,
                                    location_lon = row["lon"].toFloat().Value,
                                    formatted_addr = row["formatted_location"].ToString()
                                };
                                nearbyPeople.Add(person);
                            }
                            response.userinfo = nearbyPeople;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string createDiscussionGroup(long uid, string title, float lat, float lon)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_create_discussion_group";
                    cmd.Parameters.Add("@uid", SqlDbType.BigInt).Value = uid;
                    cmd.Parameters.Add("@title", SqlDbType.VarChar).Value = title;
                    cmd.Parameters.Add("@location_lat", SqlDbType.Float).Value = lat;
                    cmd.Parameters.Add("@location_lon", SqlDbType.Float).Value = lon;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["return"].Value.toInt32().Value;
                        if (returnVal == -1)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_NEARBY_DISCUSSTIONGROUP_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_NEARBY_DISCUSSTIONGROUP_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string dismissDiscussionGroupReq(long created_owner, string grp_id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_dismiss_discusstion_group";
                    cmd.Parameters.Add("@owner_id", SqlDbType.BigInt).Value = created_owner;
                    cmd.Parameters.Add("@grp_id", SqlDbType.Int).Value = grp_id;
                    cmd.Parameters.Add(@"return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal == -1)
                        {
                            response.errCode = ErrorCodes.CODE_ERR_ON_NEARBY_DISCUSSTIONGROUP_DELETE_FAIL;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_NEARBY_DISCUSSTIONGROUP_DELETE_FAIL;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string requestNearByGroups(long uid, double lat, double lon, double distance_filter)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_location_get_proper_nearby";
                    cmd.Parameters.Add("@uid", SqlDbType.BigInt).Value = uid;
                    cmd.Parameters.Add("@lat", SqlDbType.Float).Value = lat;
                    cmd.Parameters.Add("@lon", SqlDbType.Float).Value = lon;
                    cmd.Parameters.Add("@distance_filter", SqlDbType.Float).Value = distance_filter;
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("nearby");
                            dt.Load(dr);
                            List<user_nearby> nearbyPeople = new List<user_nearby>();
                            foreach (DataRow row in dt.Rows)
                            {
                                user_nearby person = new user_nearby()
                                {
                                    uid = row["uid"].toInt64().Value,
                                    nickname = row["nickname"].ToString(),
                                    phone = row["phone"].toInt64().Value,
                                    region_id = row["region_id"].toInt32().Value,
                                    headicon = row["headicon_img_path"].ToString(),
                                    location_lat = row["lat"].toFloat().Value,
                                    location_lon = row["lon"].toFloat().Value,
                                    formatted_addr = row["formatted_location"].ToString()
                                };
                                nearbyPeople.Add(person);
                            }
                            response.userinfo = nearbyPeople;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }
    }
}
